angular.module('starter.controllers',[])
    .controller('AppController', ['$scope', '$rootScope', '$state','$ionicModal', '$ionicHistory', '$ionicPopup', 'Page','XCode', 'ApiEndpoint',
        function ($scope, $rootScope, $state,$ionicModal, $ionicHistory, $ionicPopup, Page, XCode, ApiEndpoint) {


            XCode.init();

            var date = new Date();
            var now = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
            $scope.basicDate = now;
            //$scope.url = {http:'http://58.52.161.94:8080/env/'};
            //$scope.url = {http:'http://10.0.1.202:10060/env/'};
            $scope.url = ApiEndpoint.url;

            $scope.$on('$viewContentLoaded', function () {
            });

            // 重新登录
            $rootScope.$on('userLoginIntercepted', function (event, data) {
                $state.go('login');
            });

            $scope.backGo = function () {
                $ionicHistory.goBack();
            };

            /*Page.ajaxPost('mobile/getUrl.do', null, function (resp) {
             $scope.serverPath = resp.data;

             });*/

            $scope.mClick = function (url) {

                var newUrl = $scope.url + url;
                //var newUrl = $scope.serverPath + url;

                var open = cordova.plugins.disusered.open;

                function success() {
                    console.log('Success');
                }

                function error(code) {
                    if (code == 1) {
                        var alertPopup = $ionicPopup.alert({
                            title: '提示',
                            template: '不支持的文件格式，请安装相应软件',
                            okType: 'button-balanced'
                        });
                        alertPopup.then(function (res) {
                        });
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: '提示',
                            template: '未知错误',
                            okType: 'button-balanced'
                        });
                        alertPopup.then(function (res) {
                        });
                    }
                }

                cordova.plugins.disusered.open(newUrl, success, error);

            }

            $ionicModal.fromTemplateUrl('templates/my-modal.html', {
                scope: $scope,
                animation: 'slide-in-up'
            }).then(function(modal) {
                $scope.modal = modal;
            });
            $scope.openModal = function() {
                $scope.modal.show();
            };
            $scope.closeModal = function() {
                $scope.modal.hide();
            };

        }
    ])
    .controller('loginCtrl', ['$cookieStore', '$ionicListDelegate','$rootScope', '$scope', '$state', '$window', 'Page', 'XCode', '$cordovaAppVersion','$ionicPopup',
        function ($cookieStore, $ionicListDelegate,$rootScope, $scope, $state, $window, Page, XCode, $cordovaAppVersion, $ionicPopup) {

            //$scope.$on('$ionicView.afterEnter', function() {
            //    $("#userCode").focus().trigger("click");
            //});
            $scope.keyboardFLag = false;

            $scope.$on('$ionicView.afterEnter', function () {
                $scope.keyboardFLag = true;
            });

            //$scope.user = {
            //    userCode: $window.localStorage["userCode"],
            //    password: $.md5($window.localStorage["password"])
            //};

            $scope.user = {
                userCode: '001',
                password: '123456'
            };

            /*$scope.user = {userCode: $cookieStore.get("userCode"),
             password: $cookieStore.get("password")};*/
            /*$scope.user = {userCode: '',password: ''};*/

            //$rootScope.platform = {};
            //
            ////版本强制更新
            //$scope.update = function(){
            //  $scope.version = {local: '1.0.0', server: '1.0.0' };
            //
            //  $cordovaAppVersion.getVersionNumber().then(function (version) {//读取当前移动端版本
            //    $scope.version.local = version;
            //  });
            //
            //  Page.ajaxPost('mobile/getVersion.do', null, function (resp) {//读取服务器最新版本
            //    $scope.version.server = resp.data;
            //
            //    if ($scope.version.local == $scope.version.server) {
            //      $state.go('home');                                                    //直接登录
            //    } else {
            //
            //      if (device.platform != "Android") {
            //        var alertPopupIOS  = $ionicPopup.alert({
            //          title: '提示',
            //          template: '有新版本，请到应用商店升级！',
            //          okText: '确定',
            //          okType: 'button-balanced'
            //        });
            //        alertPopupIOS.then(function (res) {});
            //      }else{
            //        var alertPopup  = $ionicPopup.alert({
            //          title: '提示',
            //          template: '有新版本，请升级！',
            //          okText: '确定',
            //          okType: 'button-balanced'
            //        });
            //        alertPopup.then(function (res) {
            //          if (res) {
            //            //本机
            //            //url = 'mobile/update.do?path=C:/XZY/Java/Workspace/EastDigit/mobile/platforms/android/build/outputs/apk/android-debug.apk&filename=android-debug.apk';
            //            //202
            //            //url = 'mobile/update.do?path=/home/apache-tomcat-env/webapps/env/assets/soft/env_android.apk&filename=env_android.apk';
            //            //生产
            //            url = 'mobile/update.do?path=/home/tester/tomcat/webapps/env/assets/soft/env_android.apk&filename=env_android.apk';
            //
            //            var newUrl = $scope.url + url;
            //
            //            var ret = cordova.plugins.disusered.open(newUrl, success, error);
            //
            //            function success() {
            //              console.log('Success');
            //            }
            //
            //            function error(code) {
            //              if (code == 1) {
            //                var alertPopup = $ionicPopup.alert({
            //                  title: '提示',
            //                  template: '不支持的文件格式，请安装相应软件',
            //                  okType: 'button-balanced'
            //                });
            //                alertPopup.then(function (res) {
            //                });
            //              } else {
            //                var alertPopup = $ionicPopup.alert({
            //                  title: '提示',
            //                  template: '未知错误',
            //                  okType: 'button-balanced'
            //                });
            //                alertPopup.then(function (res) {
            //                });
            //              }
            //            }
            //          }
            //        });
            //      }
            //    }
            //  });
            //};

            //$scope.$watch('user.file',function(newValue,oldValue, scope){
            //    if(newValue != undefined) {
            //        setTimeout(function(){
            //            console.log($scope);
            //        },200)
            //
            //    }
            //});
            //$scope.uploadFile = function() {
            //    Page.notice(111);
            //}
            //
            //function getLocation(){
            //    if (navigator.geolocation){
            //        navigator.geolocation.getCurrentPosition(showPosition,showError);
            //    }else{
            //        alert("浏览器不支持地理定位。");
            //    }
            //}
            //
            //function showPosition(position){
            //    $("#latlon").html("纬度:"+position.coords.latitude +'，经度:'+ position.coords.longitude);
            //    var latlon = position.coords.latitude+','+position.coords.longitude;
            //
            //    //baidu
            //    var url = "http://api.map.baidu.com/geocoder/v2/?ak=C93b5178d7a8ebdb830b9b557abce78b&callback=renderReverse&location="+latlon+"&output=json&pois=0";
            //    $.ajax({
            //        type: "GET",
            //        dataType: "jsonp",
            //        url: url,
            //        beforeSend: function(){
            //            $("#baidu_geo").html('正在定位...');
            //        },
            //        success: function (json) {
            //            if(json.status==0){
            //                $("#baidu_geo").html(json.result.formatted_address);
            //            }
            //        },
            //        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //            $("#baidu_geo").html(latlon+"地址位置获取失败");
            //        }
            //    });
            //}
            //
            //function showError(error){
            //    switch(error.code) {
            //        case error.PERMISSION_DENIED:
            //            alert("定位失败,用户拒绝请求地理定位");
            //            break;
            //        case error.POSITION_UNAVAILABLE:
            //            alert("定位失败,位置信息是不可用");
            //            break;
            //        case error.TIMEOUT:
            //            alert("定位失败,请求获取用户位置超时");
            //            break;
            //        case error.UNKNOWN_ERROR:
            //            alert("定位失败,定位系统失效");
            //            break;
            //    }
            //}
            //
            //getLocation();

            $(".file").on("change","input[type='file']",function(){
                var filePath=$(this).val();
                if(filePath.indexOf("jpg")!=-1 || filePath.indexOf("png")!=-1){
                    $(".fileerrorTip").html("").hide();
                    var arr=filePath.split('\\');
                    var fileName=arr[arr.length-1];
                    $(".showFileName").html(fileName);
                }else{
                    $(".showFileName").html("");
                    $(".fileerrorTip").html("您未上传文件，或者您上传文件类型有误！").show();
                    return false
                }
            })

            $scope.login = function () {
                //点击登录，就清缓存
                //Page.ajaxPost('user/logout.do', null, function (resp) {

                    $window.sessionStorage.clear();// 删除sessionStorage
                    var data = {userCode: $scope.user.userCode, password: $.md5($scope.user.password)};

                    Page.ajaxPost('less/user/login.do', data, function (resp) {
                        //$rootScope.user = resp.data.user;
                        //$rootScope.user.token = resp.data.sid;
                        //$window.sessionStorage["user"] = angular.toJson($rootScope.user);
                        //
                        ///*$cookieStore.put("userCode",$scope.user.userCode);
                        // $cookieStore.put("password",$scope.user.password);*/
                        //
                        //$window.localStorage["userCode"] = $scope.user.userCode;
                        //$window.localStorage["password"] = $scope.user.password;
                        //
                        //try {
                        //    //启动极光推送服务
                        //    window.plugins.jPushPlugin.init();
                        //
                        //    //开启调试模式
                        //    if (device.platform != "Android") {//ios
                        //        window.plugins.jPushPlugin.setBadge(0);//登录后，角标清0
                        //        //window.plugins.jPushPlugin.setDebugModeFromIos();//设置成开发模式
                        //        window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);//角标样式
                        //    } else {//android
                        //        window.plugins.jPushPlugin.setDebugMode(false);//设置调试模式
                        //    }
                        //
                        //    //设置本机别名
                        //    window.plugins.jPushPlugin.setAlias($rootScope.user.id);
                        //
                        //} catch (exception) {
                        //    console.log(exception);
                        //}
                        window.mobileData = "";
                        resp.data.user.token = resp.data.token;
                        $window.sessionStorage["user"] = angular.toJson(resp.data.user);
                        window.mobileData = window.mobileData + "userId=" + resp.data.user.id + "&token=" + resp.data.token;
                        $rootScope.userId = resp.data.user.id;
                        $rootScope.token = resp.data.token;
                        //$rootScope._timestamp = resp.data._timestamp;
                        //$rootScope._nonce = resp.data._nonce;

                        XCode.init();
                        //$scope.update();
                        $state.go('home');
                    });
                //});

                /*测试*/
                /*$state.go('home');
                 $rootScope.user = data;*/
            }
        }
    ])

    .controller('homeCtrl', ['$scope', '$http', '$ionicSlideBoxDelegate', 'Page',
        function ($scope, $http, $ionicSlideBoxDelegate, Page) {
            $scope.edit = false;
            $scope.doRefresh = function () {
                console.log('下拉刷新')
                //停止刷新
                $scope.$broadcast('scroll.refreshComplete');
            }

            //$scope.onTouch = function (event) {
            //    $scope.pos = event.currentTarget.getAttributeNode('pos').value;
            //}
            //
            //$scope.onRelease = function (event) {
            //    $scope.pos = "p0";
            //}
        }
    ])

    .controller('docCtrl', ['$rootScope', '$scope', '$stateParams', 'Page', '$ionicScrollDelegate', '$state', '$ionicHistory',
        function ($rootScope, $scope, $stateParams, Page, $ionicScrollDelegate, $state, $ionicHistory) {

            $ionicScrollDelegate.scrollTop();
            $scope.isActive = 'recv';
            $scope.title = '我的公文';

            $scope.init = function () {
                Page.ajaxPost('docReceive/myReceiveStart.do', null, function (resp) {

                    $scope.recvs = resp.data.rows;
                });
            }
            $scope.init();

            $scope.doRefresh = function () {
                console.log('下拉刷新')
                if ($scope.edit) {
                    $scope.$broadcast('scroll.refreshComplete');
                    return;
                }
                if ($scope.isActive == 'recv') {
                    Page.ajaxPost('docReceive/myReceiveStart.do', null, function (resp) {
                        $scope.recvs = resp.data.rows;
                    });
                } else {
                    Page.ajaxPost('docSend/mySendStart.do', null, function (resp) {
                        console.log(resp);
                        $scope.sends = resp.data.rows;
                    });
                }
                //停止刷新
                $scope.$broadcast('scroll.refreshComplete');
            }


            $scope.backGo = function () {
                if ($scope.edit) {
                    $scope.edit = false;
                    $ionicScrollDelegate.scrollTop();
                    $scope.title = '我的公文';
                } else {
                    $state.go('home');
                }
            };

            $scope.changeTab = function (evt) {
                $scope.edit = false;
                var elem = evt.currentTarget;
                $scope.isActive = elem.getAttributeNode('data-active').value;
                $ionicScrollDelegate.resize();

                if ($scope.isActive == 'recv') {
                    Page.ajaxPost('docReceive/myReceiveStart.do', null, function (resp) {
                        $scope.recvs = resp.data.rows;
                    });
                } else {
                    Page.ajaxPost('docSend/mySendStart.do', null, function (resp) {
                        console.log(resp);
                        $scope.sends = resp.data.rows;
                    });
                }
            };

            $scope.show = function (obj) {
                if ($scope.fields) {
                    $scope.fields = null;
                }

                var data = {id: obj.processInstanceId};
                if ($scope.isActive == 'recv') {
                    data.moduleId = 'doc_received';
                } else {
                    data.moduleId = 'doc_send';
                }
                Page.ajaxPost('mobile/getModule.do', data, function (resp) {
                    $scope.fields = resp.data;
                    console.log(obj);
                    for (var i = 0; i < $scope.fields.length; i++) {
                        if ($scope.fields[i].showType.indexOf('_') > 0) {
                            var strs = $scope.fields[i].showType.split('_');
                            $scope.fields[i].showType = strs[0];
                            $scope.fields[i].options = strs[1];
                        }

                        for (var key in $scope.fields[i]) {
                            if (obj[$scope.fields[i][key]]) {
                                $scope.fields[i].value = obj[$scope.fields[i][key]];
                            }

                            /*if (obj.form[$scope.fields[i][key]]) {
                             $scope.fields[i].value = obj.form[$scope.fields[i][key]];
                             }*/
                        }
                    }
                    if (obj.files != undefined) {
                        Page.ajaxPostQuiet('mobile/getUrl.do', null, function (resp) {
                            var nginx = resp.data;
                            for (var i = 0; i < obj.files.length; i++) {
                                obj.files[i].url = obj.files[i].url;
                            }
                        });
                        $scope.fields.files = obj.files;
                    }
                    $scope.comments = obj.comments;
                    if (data.moduleId == 'doc_send' || data.moduleId == 'doc_send_sj') {
                        $scope.title = '我的发文详情';
                    } else {
                        $scope.title = '我的收文详情';
                    }
                    if (obj.taskState.taskStatus == 'true') {
                        $scope.taskName = "流程结束";
                    } else {
                        $scope.taskName = obj.taskState.taskName;
                    }
                    $scope.edit = true;
                    $ionicScrollDelegate.scrollTop();
                });
            }
        }
    ])

    .controller('meetingCtrl', ['$rootScope', '$scope', '$stateParams', '$state', 'Page', '$ionicScrollDelegate', '$ionicHistory', '$cordovaDialogs', '$ionicPopup', '$ionicModal',
        function ($rootScope, $scope, $stateParams, $state, Page, $ionicScrollDelegate, $ionicHistory, $cordovaDialogs, $ionicPopup, $ionicModal) {

            $scope.isActive = 'waitJoin';

            $scope.init = function () {
                Page.ajaxPost('meeting/queryWaitJoin.do', null, function (resp) {
                    $scope.waitMeetings = resp.data.rows;
                });
            }

            $scope.init();

            $scope.backGo = function () {

                if ($scope.edit) {
                    $scope.edit = false;
                    $ionicScrollDelegate.scrollTop();
                } else {
                    $state.go('home');
                }
            };

            $scope.doRefresh = function () {
                console.log('下拉刷新')
                if ($scope.edit) {
                    $scope.$broadcast('scroll.refreshComplete');
                    return;
                }
                if ($scope.isActive == 'waitJoin') {
                    Page.ajaxPost('meeting/queryWaitJoin.do', null, function (resp) {
                        $scope.waitMeetings = resp.data.rows;
                    });
                } else {
                    Page.ajaxPost('meeting/alreadyJoin.do', null, function (resp) {
                        $scope.alreadyMeetings = resp.data.rows;
                    });
                }
                $scope.$broadcast('scroll.refreshComplete');

            }

            $scope.changeTab = function (value) {

                $scope.edit = false;
                //var elem = evt.currentTarget;
                //
                $scope.isActive = value;
                //
                $ionicScrollDelegate.resize();
                //
                if ($scope.isActive == 'waitJoin') {
                    Page.ajaxPost('meeting/queryWaitJoin.do', null, function (resp) {
                        $scope.waitMeetings = resp.data.rows;
                    });
                } else if ($scope.isActive == 'alreadyJoin') {
                    Page.ajaxPost('meeting/alreadyJoin.do', null, function (resp) {
                        $scope.waitMeetings = resp.data.rows;
                    });
                } else {
                    Page.ajaxPost('meeting/queryMyMeeting.do', null, function (resp) {
                        $scope.waitMeetings = resp.data.rows;
                    });
                }
            };

            $scope.showAlert = function (val) {
                var alertPopup = $ionicPopup.alert({
                    template: val,
                    okType: 'button-balanced'
                });
                alertPopup.then(function (res) {
                });
            };

            $ionicModal.fromTemplateUrl('my-modal.html', {
                scope: $scope,
                animation: 'slide-in-up'
            }).then(function (modal) {
                $scope.modal = modal;
            });


            $scope.agreeJoin = function () {
                if (!$scope.meeting.meetingId) {
                    return;
                }
                var meetStaff = {
                    "feedback": "同意参会",
                    'userId': $scope.user.id,
                    'meetingId': $scope.meeting.meetingId,
                    'feedbackTime': new Date()
                }
                Page.ajaxPost('meetStaff/update.do', meetStaff, function (resp) {
                    $scope.showAlert('反馈成功');
                });
            }


            $scope.feedMeet = function () {
                Page.ajaxPost('meetStaff/query.do', {'meetingId': $scope.meeting.meetingId}, function (resp) {
                    console.log(resp);
                    $scope.meetStaffs = resp.data.rows;
                    $scope.modal.show();
                })
            }

            $scope.refuseJoin = function () {
                if (!$scope.meeting.meetingId) {
                    return;
                }
                $scope.meetStaff = {
                    "feedback": "拒绝参会",
                    'userId': $scope.user.id,
                    'meetingId': $scope.meeting.meetingId,
                    'feedbackTime': new Date()
                }
                // An elaborate, custom popup
                var myPopup = $ionicPopup.show({
                    template: '<textarea type="text" ng-model="meetStaff.reason"></textarea>',
                    title: '请填写拒绝参会原因',
                    scope: $scope,
                    buttons: [
                        {
                            text: '<b>提交</b>',
                            type: 'button-positive',
                            onTap: function (e) {
                                console.log($scope.meetStaff);
                                $scope.showAlert('反馈成功');
                                return;
                                Page.ajaxPost('meetStaff/update.do', $scope.meetStaff, function (resp) {
                                    $scope.showAlert('反馈成功');
                                    $scope.meetStaff = {};
                                });
                            }
                        }, {text: '取消'}
                    ]
                });
                myPopup.then(function (res) {
                    console.log('Tapped!', res);
                });


            }


            $scope.show = function (obj) {


                if ($scope.meetingFields) {
                    $scope.meetingFields = null;
                }

                var data = {
                    moduleId: 'huiyiguanli',
                    id: obj.processInstanceId
                };


                Page.ajaxPost('meetStaff/query.do', obj, function (resp) {
                    var data = resp.data.rows;
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].userId == $scope.user.id) {
                            if (data[i].feedback) {
                                $scope.respMeet = true;
                                $scope.feedback = data[i];
                                break;
                            }
                        }
                    }
                })

                Page.ajaxPost('mobile/getModule.do', data, function (resp) {
                    $scope.meetingFields = resp.data;
                    console.log(obj);
                    $scope.meeting = obj;
                    for (var i = 0; i < $scope.meetingFields.length; i++) {
                        if ($scope.meetingFields[i].showType.indexOf('_') > 0) {
                            var strs = $scope.meetingFields[i].showType.split('_');
                            $scope.meetingFields[i].showType = strs[0];
                            $scope.meetingFields[i].options = strs[1];
                        }
                        for (var key in $scope.meetingFields[i]) {
                            if (obj[$scope.meetingFields[i][key]]) {
                                $scope.meetingFields[i].value = obj[$scope.meetingFields[i][key]];
                            }
                        }
                    }
                    if (obj.files != undefined) {
                        Page.ajaxPostQuiet('mobile/getUrl.do', null, function (resp) {
                            var nginx = resp.data;
                            for (var i = 0; i < obj.files.length; i++) {
                                obj.files[i].url = obj.files[i].url;
                            }
                        });
                        $scope.meetingFields.files = obj.files;
                    }
                    if (obj.taskState.taskStatus == 'true') {
                        $scope.taskName = "流程结束";
                    } else {
                        $scope.taskName = obj.taskState.taskName;
                    }
                    $scope.edit = true;
                    $ionicScrollDelegate.scrollTop();
                });
            }
        }
    ])

    .controller('waitdoCtrl', ['$rootScope', '$scope', '$stateParams', '$ionicModal', '$state', 'Page', '$ionicPopup', '$ionicScrollDelegate',
        function ($rootScope, $scope, $stateParams, $ionicModal, $state, Page, $ionicPopup, $ionicScrollDelegate) {
            $scope.title = "我的待办";
            $scope.isActive = 'detail';

            $scope.init = function (_pageSize, _pageIndex) {
                Page.ajaxPost('waitdo/appTasks.do', {
                    '_pageSize': _pageSize,
                    '_pageIndex': _pageIndex
                }, function (resp) {
                    if($scope.moreData){//是上拉加载调用
                        $ionicScrollDelegate.scrollBy(0, -10);
                    }else{
                        $ionicScrollDelegate.scrollTop();
                    }
                    $scope.waitdos = resp.data.rows;
                    console.log(resp.data.total);
                    if(resp.data.total <= $scope._pageSize){
                         $scope.moreData = true;
                        $scope.infiniteText = '没有需要加载的数据';
                    }else{
                        $scope.moreData = false;
                        $scope.infiniteText = '下拉加载更多';
                    }
                });
            }

            $scope.backGo = function () {
                if ($scope.edit) {
                    $scope.edit = false;
                    $scope.title = "我的待办";
                    $ionicScrollDelegate.scrollTop();
                } else if ($scope.selectAssignee) {
                    $scope.selectAssignee = false;
                    $scope.edit = true;
                    $scope.title = "我的待办";
                    $ionicScrollDelegate.scrollTop();
                } else {
                    $state.go('approve');
                }
            };

            $scope.changeTab = function (evt) {
                var elem = evt.currentTarget;
                $scope.isActive = elem.getAttributeNode('data-active').value;
                $ionicScrollDelegate.resize();
            };

            $scope.doRefresh = function () {
                console.log('下拉刷新')
                $scope.init($scope._pageSize, $scope._pageIndex);
                //停止刷新
                $scope.$broadcast('scroll.refreshComplete');
            }

            $scope.show = function (waitdo) {
                if ($scope.fields) {
                    $scope.fields = null;
                }
                $scope.task = waitdo;


                $scope.properties = angular.copy($scope.task.properties.properties);
                if ($scope.properties && $scope.properties.length > 0) {
                    $($scope.properties).each(function (index, property) {
                        if (property.id == 'comment_send_huiBanDuiShiAudit' && property.readable && property.writable) {
                            $scope.task.form.showVote = true;
                            $scope.task.form.send_huiBanDuiShiAuditVote = false;
                        }
                    });
                }


                var data = {
                    id: waitdo.processInstanceId,
                    moduleId: waitdo.processDefinitionId.substr(0, waitdo.processDefinitionId.indexOf(":"))
                }
                /*if (waitdo.processDefinitionId.indexOf("leave") != -1) {
                 data.moduleId = 1;
                 }
                 if (waitdo.processDefinitionId.indexOf("huiyi") != -1) {
                 data.moduleId = 2;
                 }
                 if (waitdo.processDefinitionId.indexOf("asset") != -1) {
                 data.moduleId = 3;
                 }
                 if (waitdo.processDefinitionId.indexOf("send") != -1) {
                 data.moduleId = 4;
                 }
                 if (waitdo.processDefinitionId.indexOf("received") != -1) {
                 data.moduleId = 5;
                 }*/
                Page.ajaxPost('mobile/getModule.do', data, function (resp) {
                    $scope.fields = resp.data;
                    for (var i = 0; i < $scope.fields.length; i++) {
                        if ($scope.fields[i].showType.indexOf('_') > 0) {
                            var strs = $scope.fields[i].showType.split('_');
                            $scope.fields[i].showType = strs[0];
                            $scope.fields[i].options = strs[1];
                        }
                        for (var key in $scope.fields[i]) {
                            if (waitdo.form[$scope.fields[i][key]]) {
                                $scope.fields[i].value = waitdo.form[$scope.fields[i][key]];
                            }
                        }


                    }
                    if (waitdo.form.files) {
                        $scope.fields.files = waitdo.form.files;
                    }
                    $scope.buttons = waitdo.buttons;
                    $scope.comments = waitdo.comments;
                    $scope.edit = true;
                    $ionicScrollDelegate.scrollTop();
                });
            }

            $scope.assignee = {};
            $scope.cc = {}

            $scope.showAlert = function () {
                var alertPopup = $ionicPopup.alert({
                    template: '提交成功',
                    okType: 'button-balanced'
                });
                alertPopup.then(function (res) {
                    $scope.edit = false;
                    $scope.init($scope._pageSize, $scope._pageIndex);
                });
            };

            $scope.selectAssignee = false;
            // 按钮事件
            $scope.approval = function (button) {

                $scope.properties = angular.copy($scope.task.properties.properties);
                if (!$scope.selectAssignee) {
                    $scope.assigneeElements = [];
                    if ($scope.properties && $scope.properties.length > 0) {
                        $($scope.properties).each(function (index, property) {

                            if ((property.type.name === 'userSelect' || property.type.name === 'userMultiSelect')
                                && property.id.indexOf(button.id) != -1) {
                                $scope.assigneeElements[$scope.assigneeElements.length] = {
                                    id: property.id,
                                    name: property.name,
                                    type: property.type.name,
                                    value: ''
                                };
                            }
                        });
                    }
                }

                if (!$scope.selectAssignee && $scope.assigneeElements.length > 0) {
                    $scope.selectAssignee = true;
                    $scope.currentButton = button;
                    $scope.selectAssignee = true;
                    $scope.edit = false;
                    if ($scope.assigneeElements[0].type == 'userSelect') {
                        $scope.selectMultiple = false;
                    } else if ($scope.assigneeElements[0].type == 'userMultiSelect') {
                        $scope.selectMultiple = true;
                    }
                } else {// 提交
                    var replaceData = angular.copy($scope.task.form);
                    replaceData.send_huiBanDuiShiAuditVote = !replaceData.send_huiBanDuiShiAuditVote;
                    if ($scope.selectAssignee) {
                        if ($scope.assignee) {
                            if ($scope.assignee.falseAssignee) {
                                $scope.assigneeElements[0].value = $scope.assignee.falseAssignee;
                            } else if ($scope.assignee.trueAssignee) {
                                $scope.assigneeElements[0].value = $scope.assignee.trueAssignee;
                            }
                        }
                        var assigneeFlag = false;
                        $($scope.assigneeElements).each(function (index, element) {
                            replaceData[element.id] = element.value;
                            if (element.value != '') {
                                assigneeFlag = true;
                            }
                        });
                        if (!assigneeFlag) {
                            Page.alert("请选择办理人!");
                            return;
                        }
                    }

                    replaceData.outcome = button.name;
                    if ($scope.task.form.timeCal != undefined) {
                        replaceData.timeCal = $scope.task.form.timeCal;
                    }
                    // 默认流程条件
                    var conditions = button.conditions;
                    for (var key in conditions) {
                        if (typeof replaceData[key] == 'undefined'
                            || replaceData[key].length == 0) {
                            replaceData[key] = conditions[key];
                        } else if (replaceData[key] != conditions[key]) {
                            Page.alert("页面取值与流程变量不一致！");
                            return;
                        }
                    }
                  replaceData.outcome = button.name || button.id;
                  Page.ajaxPost('bpm/task/' + $scope.task.id
                    + '/complete.do', {
                        properties: replaceData
                    }, function (resp) {
                        $scope.showAlert();
                        $scope.edit = false;
                        $scope.selectAssignee = false;
                        $scope.init($scope._pageSize, $scope._pageIndex);
                    });
                }
            }

        }])

    .controller('alreadydoCtrl', ['$rootScope', '$scope', '$stateParams', '$state', 'Page', '$ionicScrollDelegate', '$ionicHistory',
        function ($rootScope, $scope, $stateParams, $state, Page, $ionicScrollDelegate, $ionicHistory) {
            $scope.isActive = 'detail';
            $scope.init = function (_pageSize, _pageIndex) {
                Page.ajaxPost('waitdo/query.do', {
                        '_pageSize': _pageSize,
                        '_pageIndex': _pageIndex
                    },
                    function (resp) {
                        $scope.alreadydos = resp.data.rows;
                        if($scope.moreData){//是上拉加载调用
                            $ionicScrollDelegate.scrollBy(0, -10);
                        }else{
                            $ionicScrollDelegate.scrollTop();
                        }
                        console.log(resp.data.total);
                        if(resp.data.total <= $scope._pageSize){
                            $scope.moreData = true;
                            $scope.infiniteText = '没有需要加载的数据';
                        }else{
                            $scope.moreData = false;
                            $scope.infiniteText = '下拉加载更多';
                        }
                    });
            }


            //$scope.init = function (_pageSize, _pageIndex) {
            //    Page.ajaxPost('waitdo/appTasks.do', {
            //        '_pageSize': _pageSize,
            //        '_pageIndex': _pageIndex
            //    }, function (resp) {
            //        $ionicScrollDelegate.scrollTop();
            //        $scope.waitdos = resp.data.rows;
            //        console.log(resp.data.total);
            //        if(resp.data.total <= $scope._pageSize){
            //            $scope.moreData = true;
            //            $scope.infiniteText = '没有需要加载的数据';
            //        }else{
            //            $scope.infiniteText = '下拉加载更多';
            //        }
            //    });
            //}


            $scope.backGo = function () {
                if ($scope.edit) {
                    $scope.edit = false;
                    $ionicScrollDelegate.scrollTop();
                } else {
                    $state.go('approve');
                }
            };

            $scope.changeTab = function (evt) {
                var elem = evt.currentTarget;
                $scope.isActive = elem
                    .getAttributeNode('data-active').value;
                $ionicScrollDelegate.resize();
            };

            $scope.doRefresh = function () {
                console.log('下拉刷新')
                $scope.init($scope._pageSize, $scope._pageIndex);
                //停止刷新
                $scope.$broadcast('scroll.refreshComplete');
            }

            $scope.show = function (obj) {
                if ($scope.fields) {
                    $scope.fields = null;
                }
                var data = {
                    id: obj.processInstanceId,
                    moduleId: obj.processDefinitionId.substr(0, obj.processDefinitionId.indexOf(":"))
                }
                /*if (obj.processDefinitionId.indexOf("leave") != -1) {
                 data.moduleId = 1;
                 }
                 if (obj.processDefinitionId.indexOf("huiyi") != -1) {
                 data.moduleId = 2;
                 }
                 if (obj.processDefinitionId.indexOf("asset") != -1) {
                 data.moduleId = 3;
                 }
                 if (obj.processDefinitionId.indexOf("send") != -1) {
                 data.moduleId = 4;
                 }
                 if (obj.processDefinitionId.indexOf("received") != -1) {
                 data.moduleId = 5;
                 }*/
                Page.ajaxPost('mobile/getModule.do', data,
                    function (resp) {
                        $scope.fields = resp.data;
                        for (var i = 0; i < $scope.fields.length; i++) {
                            if ($scope.fields[i].showType.indexOf('_') > 0) {
                                var strs = $scope.fields[i].showType.split('_');
                                $scope.fields[i].showType = strs[0];
                                $scope.fields[i].options = strs[1];
                            }
                            for (var key in $scope.fields[i]) {
                                if (obj.form[$scope.fields[i][key]]) {
                                    $scope.fields[i].value = obj.form[$scope.fields[i][key]];
                                    console.log($scope.fields[i].value);
                                }
                            }
                        }
                        if (obj.form.files) {
                            $scope.fields.files = obj.form.files;
                        }
                        $scope.comments = obj.comments;
                        $scope.edit = true;
                        $ionicScrollDelegate.scrollTop();
                        $scope.isActive = 'detail';
                        console.log($scope.fields);
                    });


            }
        }])

    .controller('leaveCtrl', ['$rootScope', '$scope', '$stateParams', '$state', 'Page', '$ionicScrollDelegate', '$ionicHistory',
        function ($rootScope, $scope, $stateParams, $state, Page, $ionicScrollDelegate, $ionicHistory) {
            $scope.init = function () {
                Page.ajaxPost('leave/queryMyLeave.do', null, function (resp) {
                    $scope.leaves = resp.data.rows;
                });
            }
            $scope.init();

            $scope.backGo = function () {
                if ($scope.edit) {
                    $scope.edit = false;
                    $ionicScrollDelegate.scrollTop();
                } else {
                    $state.go('home');
                }
            };

            $scope.doRefresh = function () {
                console.log('下拉刷新')
                $scope.init();
                $scope.$broadcast('scroll.refreshComplete');
            }
            $scope.show = function (leave) {
                if ($scope.fields) {
                    $scope.fields = null;
                }

                var data = {
                    id: leave.processInstanceId,
                    moduleId: 'leaveBill'
                }

                Page.ajaxPost('mobile/getModule.do', data, function (resp) {
                    $scope.fields = resp.data;
                    for (var i = 0; i < $scope.fields.length; i++) {
                        if ($scope.fields[i].showType.indexOf('_') > 0) {
                            var strs = $scope.fields[i].showType.split('_');
                            $scope.fields[i].showType = strs[0];
                            $scope.fields[i].options = strs[1];
                        }
                        for (var key in $scope.fields[i]) {
                            if (leave[$scope.fields[i][key]]) {
                                $scope.fields[i].value = leave[$scope.fields[i][key]];
                            }
                        }
                    }
                    $scope.edit = true;
                    $ionicScrollDelegate.scrollTop();
                    if (leave.taskState.taskStatus == 'true') {
                        $scope.taskName = "流程结束";
                    } else {
                        $scope.taskName = leave.taskState.taskName;
                    }
                });
            }
        }])

    .controller('assetsCtrl', ['$rootScope', '$scope', '$stateParams', '$state', 'Page', '$ionicScrollDelegate', '$ionicHistory',
        function ($rootScope, $scope, $stateParams, $state, Page, $ionicScrollDelegate, $ionicHistory) {
            $scope.init = function () {
                Page.ajaxPost('asset/myQuery.do', null, function (resp) {
                    $scope.assets = resp.data.rows;
                });
            }
            $scope.init();

            $scope.backGo = function () {
                if ($scope.edit) {
                    $scope.edit = false;
                    $ionicScrollDelegate.scrollTop();
                } else {
                    $state.go('home');
                }
            };

            $scope.doRefresh = function () {
                console.log('下拉刷新')
                $scope.init();
                $scope.$broadcast('scroll.refreshComplete');
            }
            $scope.show = function (obj) {
                if ($scope.fields) {
                    $scope.fields = null;
                }
                var data = {
                    id: obj.processInstanceId,
                    moduleId: 'assetmanage'
                }

                Page.ajaxPost('mobile/getModule.do', data, function (resp) {
                        $scope.fields = resp.data;

                        for (var i = 0; i < $scope.fields.length; i++) {
                            if ($scope.fields[i].showType.indexOf('_') > 0) {
                                var strs = $scope.fields[i].showType.split('_');
                                $scope.fields[i].showType = strs[0];
                                $scope.fields[i].options = strs[1];
                            }
                            for (var key in $scope.fields[i]) {
                                if (obj[$scope.fields[i][key]]) {
                                    $scope.fields[i].value = obj[$scope.fields[i][key]];
                                }
                            }
                        }
                        $scope.edit = true;
                        $ionicScrollDelegate.scrollTop();
                        if (obj.taskState.taskStatus == 'true') {
                            $scope.taskName = "流程结束";
                        } else {
                            $scope.taskName = obj.taskState.taskName;
                        }

                    }
                    , function () {
                        Page.alert("获取失败")
                    });
            }
        }])

    .controller('approveCtrl', ['$rootScope', '$scope', '$stateParams', '$state', 'Page', '$ionicScrollDelegate', '$ionicHistory',
        function ($rootScope, $scope, $stateParams, $state, Page, $ionicScrollDelegate, $ionicHistory) {
            $scope.backGo = function () {
                $state.go('home');
            };

            $scope.doRefresh = function () {
                console.log('下拉刷新')
                $scope.$broadcast('scroll.refreshComplete');
            }

            $scope.onTouch = function (event) {
                $scope.pos = event.currentTarget.getAttributeNode('pos').value;
            }

            $scope.onRelease = function (event) {
                $scope.pos = "p0";
            }
        }])

    .controller('leaveApplyCtrl', ['$rootScope', '$scope', '$stateParams', '$state', '$cordovaDatePicker', '$ionicHistory', 'Page', '$ionicPopup',
        function ($rootScope, $scope, $stateParams, $state, $cordovaDatePicker, $ionicHistory, Page, $ionicPopup) {
            $scope.leave = {};
            $scope.backGo = function () {
                $ionicHistory.goBack();
            };

            $scope.doRefresh = function () {
                console.log('下拉刷新')
                $scope.$broadcast('scroll.refreshComplete');
            }

            $scope.showAlert = function (val) {
                var alertPopup = $ionicPopup.alert({
                    template: val,
                    okType: 'button-balanced'
                });
                alertPopup.then(function (res) {
                });
            };

            $scope.apply = function () {
                if (!$scope.leave.leaveType) {
                    $scope.showAlert('请填写请假类型')
                    return;
                }
                if (!$scope.leave.startTime) {
                    $scope.showAlert('请填写请假开始时间')
                    return;
                }
                if (!$scope.leave.endTime) {
                    $scope.showAlert('请填写请假结束时间')
                    return;
                }
                if (!$scope.leave.timeCal) {
                    $scope.showAlert('请填写请假时间')
                    return;
                }
                $scope.leave.creater = $scope.user.id;
                $scope.leave._service = 'leaveService';
                Page.ajaxPost('bpm/process/leaveBill/startByKey.do', {properties: $scope.leave}, function (resp) {
                    var alertPopup = $ionicPopup.alert({
                        template: '发起成功',
                        okType: 'button-balanced'
                    });
                    alertPopup.then(function (res) {
                        $state.go('approve');
                    });

                }, function (error) {

                });
            }

            $scope.change = function () {
                if (isNaN($scope.leave.timeCal)) {
                    $scope.showAlert("请填写正确的请假时间");
                }
            }

        }])

    .controller('myStartedCtrl', ['$rootScope', '$scope', '$stateParams', '$state', 'Page', '$ionicScrollDelegate',
        function ($rootScope, $scope, $stateParams, $state, Page, $ionicScrollDelegate) {
            $scope.isActive = 'detail';

            $scope.init = function (_pageSize, _pageIndex) {
                Page.ajaxPost('waitdo/myStartPro.do',{
                        '_pageSize': _pageSize,
                        '_pageIndex': _pageIndex
                    },
                    function (resp) {
                        if($scope.moreData){//是上拉加载调用
                            $ionicScrollDelegate.scrollBy(0, -10);
                        }else{
                            $ionicScrollDelegate.scrollTop();
                        }
                        $scope.myStarteds = resp.data.rows;
                        if(resp.data.total <= $scope._pageSize){
                            $scope.moreData = true;
                            $scope.infiniteText = '没有需要加载的数据';
                        }else{
                            $scope.moreData = false;
                            $scope.infiniteText = '下拉加载更多';
                        }
                    });
            }


            $scope.backGo = function () {
                if ($scope.edit) {
                    $scope.edit = false;
                    $ionicScrollDelegate.scrollTop();
                } else {
                    $state.go('approve');
                }
            };


            $scope.changeTab = function (evt) {
                var elem = evt.currentTarget;
                $scope.isActive = elem
                    .getAttributeNode('data-active').value;
                $ionicScrollDelegate.resize();
            };
            $scope.doRefresh = function () {
                console.log('下拉刷新')
                $scope.init($scope._pageSize, $scope._pageIndex);
                $scope.$broadcast('scroll.refreshComplete');
            }

            $scope.show = function (obj) {
                if ($scope.fields) {
                    $scope.fields = {};
                }
                if ($scope.comments) {
                    $scope.comments = {};
                }
                var data = {
                    id: obj.processInstanceId,
                    moduleId: obj.processDefinitionId.substr(0, obj.processDefinitionId.indexOf(":"))
                }
                /*if (obj.processDefinitionId.indexOf("leave") != -1) {
                 data.moduleId = 1;
                 }
                 if (obj.processDefinitionId.indexOf("huiyi") != -1) {
                 data.moduleId = 2;
                 }
                 if (obj.processDefinitionId.indexOf("asset") != -1) {
                 data.moduleId = 3;
                 }
                 if (obj.processDefinitionId.indexOf("send") != -1) {
                 data.moduleId = 4;
                 }
                 if (obj.processDefinitionId.indexOf("received") != -1) {
                 data.moduleId = 5;
                 }*/
                Page.ajaxPost('mobile/getModule.do', data,
                    function (resp) {
                        $scope.isActive = 'detail';
                        $scope.fields = resp.data;
                        for (var i = 0; i < $scope.fields.length; i++) {
                            if ($scope.fields[i].showType.indexOf('_') > 0) {
                                var strs = $scope.fields[i].showType.split('_');
                                $scope.fields[i].showType = strs[0];
                                $scope.fields[i].options = strs[1];
                            }
                            for (var key in $scope.fields[i]) {
                                if (obj.form[$scope.fields[i][key]]) {
                                    $scope.fields[i].value = obj.form[$scope.fields[i][key]];
                                }
                            }
                        }
                        if (obj.form.files) {
                            $scope.fields.files = obj.form.files;
                        }
                        $scope.comments = obj.comments;
                        $scope.edit = true;
                        $scope.taskName = obj.name;
                        $ionicScrollDelegate.scrollTop();
                    });
            }
        }])

    .controller('cloudSpaceCtrl', ['$rootScope', '$scope', '$state', 'Page', '$cordovaFileOpener2', '$ionicPopup',
        function ($rootScope, $scope, $state, Page, $cordovaFileOpener2, $ionicPopup) {
            $scope.backGo = function () {
                $state.go('home');
            };

            $scope.doRefresh = function () {
                console.log('下拉刷新')
                $scope.init();
                $scope.$broadcast('scroll.refreshComplete');
            }

            $scope.init = function () {
                Page.ajaxPost('cloud/file/query.do', null, function (resp) {
                    console.log(resp);
                    $scope.myDocs = resp.data.rows;
                });
            }

            $scope.init();


            /*Page.ajaxPost('mobile/getUrl.do', null, function (resp) {
             $scope.nginx = resp.data;

             });

             $scope.mClick = function (url) {

             var newUrl = $scope.nginx + url;

             var open = cordova.plugins.disusered.open;

             function success() {
             console.log('Success');
             }

             function error(code) {
             if (code.code == 1) {
             var alertPopup = $ionicPopup.alert({
             title: '提示',
             template: '不支持的文件格式，请安装相应软件',
             okType: 'button-balanced'
             });
             alertPopup.then(function (res) {
             });
             } else {
             var alertPopup = $ionicPopup.alert({
             title: '提示',
             template: '未知错误',
             okType: 'button-balanced'
             });
             alertPopup.then(function (res) {
             });
             }
             }

             cordova.plugins.disusered.open(newUrl, success, error);
             }*/

        }])

    .controller('myInfoCtrl', ['$rootScope', '$scope', '$stateParams', '$state', '$window', '$ionicPopup', '$cordovaAppVersion', '$ionicLoading', 'Page', 'ApiEndpoint',
        function ($rootScope, $scope, $stateParams, $state, $window, $ionicPopup, $cordovaAppVersion, $ionicLoading, Page, ApiEndpoint) {

            $scope.version = {
                local: '1.0.0',
                server: '1.0.0'
            }


            $scope.init = function () {
                Page.ajaxPost('mobile/queryUser.do', {userId: $scope.user.id}, function (resp) {
                    $scope.user.gender = resp.data[0].gender;
                    console.log(resp);
                });

                Page.ajaxGet('department/ofUser.do', {userId: $scope.user.id}, function (resp) {
                    $scope.user.deptName = resp.data[0].deptName;
                    console.log(resp.data);

                });

                //读取当前移动端版本
                $scope.version.local = '1.0.0';
                $cordovaAppVersion.getVersionNumber().then(function (version) {
                    $scope.version.local = version;
                });

                //读取服务器最新版本
                Page.ajaxPost('mobile/getVersion.do', null, function (resp) {
                    $scope.version.server = resp.data;
                });

            }
            $scope.init();

            $scope.backGo = function () {
                //$ionicLoading.hide();
                $state.go('home');
            };

            $scope.logout = function () {// 退出登录
                Page.ajaxPost('user/logout.do', null, function (resp) {
                    $window.sessionStorage.clear();// 删除sessionStorage
                    $state.go("login");//跳转到登录界面
                });
            }
            $scope.doRefresh = function () {
                //$scope.pulltextchange = "下拉刷新";
                //console.log('下拉刷新')
                $scope.$broadcast('scroll.refreshComplete');
            }

            $scope.update = function () {

              if (device.platform == "Android") {
                //判断是否最新版本
                if ($scope.version.local == $scope.version.server) {
                  var alertPopup = $ionicPopup.alert({
                    title: '提示',
                    template: '当前已是最新版本！',
                    okType: 'button-balanced'
                  });
                  alertPopup.then(function (res) {
                  });
                } else {
                  var confirmPopup = $ionicPopup.confirm({
                    title: '提示',
                    template: '是否升级？',
                    okText: '是',
                    okType: 'button-balanced',
                    cancelText: '否',
                    cancelType: 'button-balanced'
                  });
                  confirmPopup.then(function (res) {
                    if (res) {
                      //本机
                      //url = 'mobile/update.do?path=C:/XZY/Java/Workspace/EastDigit/mobile/platforms/android/build/outputs/apk/android-debug.apk&filename=android-debug.apk';
                      //202
                      //url = 'mobile/update.do?path=/home/apache-tomcat-7-jenkins/webapps/env/assets/soft/env_android.apk&filename=env_android.apk';
                      //生产
                      url = 'mobile/update.do?path=/home/tester/tomcat/webapps/env/assets/soft/env_android.apk&filename=env_android.apk';

                      var newUrl = $scope.url + url;

                      var ret = cordova.plugins.disusered.open(newUrl, success, error);

                      function success() {
                        console.log('Success');

                        /*$ionicLoading.show({
                         template: '正在升级...'
                         });*/

                      }

                      function error(code) {
                        if (code == 1) {
                          var alertPopup = $ionicPopup.alert({
                            title: '提示',
                            template: '不支持的文件格式，请安装相应软件',
                            okType: 'button-balanced'
                          });
                          alertPopup.then(function (res) {
                          });
                        } else {
                          var alertPopup = $ionicPopup.alert({
                            title: '提示',
                            template: '未知错误',
                            okType: 'button-balanced'
                          });
                          alertPopup.then(function (res) {
                          });
                        }
                      }
                    }
                  });
                }
              }
            }
        }])

    .controller('messageCtrl', ['$rootScope', '$scope', '$stateParams', '$state', 'Page', '$ionicScrollDelegate', '$ionicPopup', '$ionicHistory',
        function ($rootScope, $scope, $stateParams, $state, Page, $ionicScrollDelegate, $ionicPopup, $timeout, $ionicHistory) {

            //$scope.items = [{
            //  text: 'A'
            //},{
            //  text: 'B'
            //}];

            //$scope.addItem = function() {
            //  $scope.items.push({
            //    text: 'C'
            //  });
            //  $ionicListDelegate.showDelete(false);
            //  setTimeout(function(){
            //    $ionicListDelegate.showDelete(true);
            //    $scope.$apply();
            //  }, 0);
            //};

            $scope.infos = [];
            $scope.add = function (event, item) {
                if ($(event.currentTarget.childNodes[0]).attr('checked')) {
                    $(event.currentTarget.childNodes[0]).removeAttr('checked');
                    for (var i = 0; i < $scope.infos.length; i++) {
                        if (item == $scope.infos[i]) {
                            $scope.infos.splice(i, 1);
                            break;
                        }
                    }
                } else {
                    $(event.currentTarget.childNodes[0]).attr('checked', 'true')
                    $scope.infos.push(item);
                }
            }

            $scope.showPopup = function () {
                $scope.data = {}

            }
            $scope.showConfirm = function () {

                var confirmPopup = $ionicPopup.alert({
                    template: '要清空所有消息吗？'
                });
                confirmPopup.then(function (res) {
                    if (res) {
                        console.log('确定');
                    } else {
                        console.log('取消');
                    }
                });
            };


            $scope.isChecked = false;
            var ids = new Array();

            $scope.init = function () {
                Page.ajaxPost('jpush/getMessage.do', {msgTo: $rootScope.user.id}, function (resp) {
                    $scope.messages = resp.data.rows;

                    for (var i = 0; i < $scope.messages.length; i++) {
                        if ($scope.messages[i].status == "1") {
                            id = $scope.messages[i].id;
                            Page.ajaxPost('jpush/updateMessage.do', {id: id, status: 2}, function (resp) {
                            });
                        }
                    }

                });
            }
            $scope.init();

            //后退
            $scope.backGo = function () {
                $scope.all = false;
                $scope.showDelete = false;
                $scope.clearParams();
                if ($scope.edit) {
                    $scope.clearParams();
                    $ionicScrollDelegate.scrollTop();
                } else {
                    $state.go('myInfo');
                }
            };

            $scope.doRefresh = function () {
                $scope.clearParams();
                $scope.init();
                $scope.$broadcast('scroll.refreshComplete');
            };

            //待删除通知
            $scope.readyToDel = function (row, id, isChecked) {

                if (isChecked == "1") {
                    $scope.messages[row].ischecked = "0";
                    ids.splice(jQuery.inArray(id, ids), 1);
                    $scope.ids = ids;
                    //console.log("没选中" + id + "待删除列表：" + $scope.ids)
                } else {
                    $scope.messages[row].ischecked = "1";
                    ids.push(id);
                    $scope.ids = ids;

                    //console.log("选中" + id + "待删除列表：" + $scope.ids)
                }
            }

            //删除通知
            $scope.deleteMessage = function (idsa) {

                if ($scope.showDelete == true) {
                    if (typeof idsa != 'undefined') {
                        Page.ajaxPost('jpush/deleteMessage.do', {ids: idsa.join(",")}, function (resp) {

                            $scope.doRefresh();
                            /*ids = [];
                             $scope.all = false;*/
                            $scope.clearParams();
                        });
                    }
                }

            }

            //编辑通知
            $scope.editMessage = function () {
                $scope.showDelete = !$scope.showDelete;
                $scope.all = false;
                $scope.doRefresh();

            }

            //全选
            $scope.selectAll = function () {

                if ($scope.showDelete == true) {
                    $scope.all = true;

                    Page.ajaxPost('jpush/getMessage.do', {msgTo: $rootScope.user.id}, function (resp) {
                        $scope.messages = resp.data.rows;

                        ids = [];
                        for (var i = 0; i < $scope.messages.length; i++) {
                            ids.push($scope.messages[i].id);
                            $scope.messages[i].ischecked = "1";
                            $scope.ids = ids;
                        }
                    });
                }

            }

            //清空各种参数
            $scope.clearParams = function () {
                $scope.all = false;
                ids = [];
                $scope.ids = ids;
            }

        }])

    .controller('signInCtrl', ['$cordovaGeolocation', '$rootScope', '$scope', '$state', 'Page', '$ionicScrollDelegate', '$ionicPopup',
        function ($cordovaGeolocation, $rootScope, $scope, $state, Page, $ionicScrollDelegate, $ionicPopup) {
            $scope.title = "签到";
            $scope.to1 = {};
            $scope.positions = {}; //所有附近位置资源
            $scope.fixedPos = {}; //选定的位置
            $scope.fixedPosTmp = {}; //选定的位置(临时存放用户选择的位置)
            $scope.point = {};   //要显示的位置点（lat,lng）
            $scope.map = {};    //地图缩略图
            $scope.mapAdjust = {} //地图调整界面
            $scope.overLay = {}; //覆盖物
            $scope.marker = {};  //标记
            $scope.label = {};   //标签
            $scope.adjust = false; //是否为位置调整界面

            $scope.currentDate = new Date();
            $scope.index = 0;

            //获得GPS坐标
            var posOptions = {timeout: 10000, enableHighAccuracy: true};
            $cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
                $scope.point.lat = position.coords.latitude
                $scope.point.lng = position.coords.longitude

                var gpsPoint = new BMap.Point($scope.point.lng, $scope.point.lat);

                /*大众版*/
                /*BMap.Convertor.translate(gpsPoint,0, $scope.translateCallback )*/

                /*极速版*/
                var url = "http://api.map.baidu.com/geoconv/v1/?coords=" +
                    $scope.point.lng +
                    "," +
                    $scope.point.lat +
                    "&from=1&to=5&ak=uTTNx6sxWxv4Z906wVilsycD&callback=?"

                $.getJSON(url, function (ret) {
                    var point = new BMap.Point(ret.result[0].x, ret.result[0].y);
                    $scope.translateCallback(point)
                });

            }, function (err) {
                switch (err.code) {
                    case 1 :
                        alert("请开启GPS功能");//用户选了不允许
                        break;
                    case 2:
                        alert("网络中断，与GPS卫星失去连接");//连不上GPS卫星，或者网络断了
                        break;
                    case 3:
                        alert("超时");//超时
                        break;
                    default:
                        alert("未知错误");//未知错误，其实是err.code==0的时候
                        break;
                }
            });

            $scope.translateCallback = function (point) {
                $scope.point = point;
                $scope.getPois(point);

            }

            $scope.getPois = function (point) {
                var geoc = new BMap.Geocoder();
                geoc.getLocation(point, function (resp) {
                    $scope.positions = resp.surroundingPois;
                    $rootScope.$apply(function () {
                        $scope.fixedPos = $scope.positions[0];
                        $scope.fixedPosTmp = $scope.fixedPos;
                    })
                    //var position = resp.surroundingPois[0];

                    /*大众版*/
                    //$scope.label = new BMap.Label(position.title,{offset:new BMap.Size(-20,-20)});
                    /*极速版*/


                    $scope.createMap(point);
                    /*setTimeout(function(){
                     $scope.createMap(point);
                     }, 200);*/
                });
            }

            $scope.createMap = function (point) {
                $scope.map = new BMap.Map("bdmapMini", {enableMapClick: false});
                $scope.map.centerAndZoom(point, 15);
                $scope.marker = new BMap.Marker(point);
                $scope.map.clearOverlays();
                $scope.map.addOverlay($scope.marker);
                $scope.map.setCenter(point);
                $scope.map.disableDragging();
                //$scope.map.disableScrollWheelZoom(); //大众版
                //$scope.map.disableDoubleClickZoom(); //大众版
                //$scope.map.disablePinchToZoom(); //大众版
            }

            $scope.createMapAdjust = function (point) {
                $scope.mapAdjust = new BMap.Map("bdmap", {enableMapClick: false});
                $scope.mapAdjust.centerAndZoom(point, 15);
                $scope.mapAdjust.addControl(new BMap.ScaleControl());
                $scope.marker = new BMap.Marker(point);
                $scope.mapAdjust.addOverlay($scope.marker);
                $scope.mapAdjust.setCenter(point);
                $scope.mapAdjust.disableDragging();
                /*大众版*/
                /*$scope.marker.setLabel($scope.label);*/
            }

            $scope.showPoint = function (position, index) {
                $scope.mapAdjust.removeOverlay($scope.marker);
                $scope.marker = new BMap.Marker(position.point);
                $scope.mapAdjust.addOverlay($scope.marker);
                $scope.mapAdjust.setCenter(position.point);
                $scope.index = index;

                /*大众版*/
                /*$scope.label = new BMap.Label(position.title,{offset:new BMap.Size(-20,-20)});
                 $scope.marker.setLabel($scope.label);*/
                /*极速版*/

                $scope.onTouch = function (event) {
                    $scope.pos = event.currentTarget.getAttributeNode('pos').value;
                }

                $scope.fixedPosTmp = position;
            }

            $scope.adjustPos = function () {
                $scope.adjust = true;
                $scope.title = '地点微调';
                setTimeout(function () {
                    $scope.createMapAdjust($scope.point);
                }, 200);

            }

            $scope.sendMessage = function (from, to, alert, date) {
                Page.ajaxPost('jpush/sendMessage.do', {
                    msgFrom: from,
                    msgTo: to,
                    alert: alert,
                    sendDate: date
                }, function (resp) {
                    var tmp = resp;
                });
            }

            $scope.signIn = function () {
                var userId = $rootScope.user.id;
                var address = $scope.fixedPos.address + "," + $scope.fixedPos.title + "(" + $scope.point.lat + "," + $scope.point.lng + ")"
                Page.ajaxPost('newSignIn/signIn.do', {
                    userId: userId,
                    signType: "2",
                    attendAddress: address
                }, function (resp) {

                    $scope.signNum = resp.data.count;
                    var retMsg = resp.data.returnMessage;

                    //if (!$scope.leave.leaveType) {
                    $scope.showAlert(retMsg)
                    return;
                    //}
                    var tmp = resp;
                });
            }

            $scope.backGo = function () {
                if ($scope.adjust) {
                    $scope.adjust = false;
                    $scope.title = '签到';
                    $ionicScrollDelegate.scrollTop();
                } else {
                    $state.go('home');
                }
            }

            $scope.reFixed = function () {
                $scope.fixedPos = $scope.fixedPosTmp;
                $scope.backGo();
            }

            $scope.onTouch = function (event) {
                $scope.pos = event.currentTarget.getAttributeNode('pos').value;
            }

            $scope.onRelease = function (event) {
                $scope.pos = "p0";
            }

            $scope.showAlert = function (val) {
                var alertPopup = $ionicPopup.alert({
                    title: '提示',
                    template: val,
                    okType: 'button-balanced'
                });
                alertPopup.then(function (res) {
                });
            };
            ;
        }])
;
